function data = gen_dyngauss_data(M, TL, n)
% Generate Dynamic Gaussian data
%
%   data = gen_dyngauss_data(M, TL, n);
%       Generate synthesized Data of Dynamic Gaussian models
%
%       Input:
%       - M:    the evolving mean vectors [d x m x (T+1)]
%       - TL:   the timelines [m x (T+1)]
%       - n:    the number of samples per-cluster per-phase
%
%       Output:
%       - data: a cell array of size 1 x (T+1). Each cell is a data
%               matrix for a time point.
%

%   Created by Dahua Lin, on Nov 24, 2010
%

%% verify input

if ~(isfloat(M) && ndims(M) == 3)
    error('gen_dyngauss_data:invalidarg', 'M should be a 3D numeric array');
end

if ~(isfloat(TL) && ndims(TL) == 2)
    error('gen_dyngauss_data:invalidarg', 'TL should be a numeric matrix.');
end

if ~(isnumeric(n) && isscalar(n) && n == fix(n) && n >= 1)
    error('gen_dyngauss_data:invalidarg', 'n should be a positive integer scalar.');
end

[d, m, t] = size(M); %#ok<ASGLU>
if ~isequal(size(TL), [m, t])
    error('gen_dyngauss_data:invalidarg', 'The size of M and TL are inconsistent.');
end

%% main

data = cell(1, t);
for i = 1 : t
    data{i} = make_data(ceil(TL(:,i) * n), M(:,:,i));
end


%% sub-functions

function X = make_data(ns, mu)

[d, m] = size(mu);
N = sum(ns);
X = zeros(d, N);

i = 0;
for k = 1 : m
    n = ns(k);
    if n > 0
        X(:, i+(1:n)) = bsxfun(@plus, mu(:,k), randn(d, n));
        i = i + n;
    end
end


